// pages/record/record.js
const util = require('../../utils/util')

Page({
  data: {
    records: [],
    loading: false,
    page: 1,
    hasMore: true
  },

  onLoad() {
    this.loadRecords()
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshRecords()
  },

  // 加载用车记录
  async loadRecords(refresh = false) {
    if (this.data.loading) return
    
    this.setData({ loading: true })
    
    try {
      const page = refresh ? 1 : this.data.page
      const res = await util.request(`/car-records?page=${page}`)
      
      if (res.code === 200) {
        const newRecords = res.data.data || []
        const records = refresh ? newRecords : [...this.data.records, ...newRecords]
        
        this.setData({
          records: records,
          page: refresh ? 2 : this.data.page + 1,
          hasMore: newRecords.length >= 10, // 假设每页10条
          loading: false
        })
      } else {
        util.showToast(res.message || '加载失败')
        this.setData({ loading: false })
      }
    } catch (error) {
      console.error('加载记录失败:', error)
      util.showToast('加载失败，请重试')
      this.setData({ loading: false })
    }
  },

  // 刷新记录
  refreshRecords() {
    this.setData({
      records: [],
      page: 1,
      hasMore: true
    })
    this.loadRecords(true)
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.refreshRecords()
    wx.stopPullDownRefresh()
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadRecords()
    }
  },

  // 查看记录详情
  viewDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/record-detail/record-detail?id=${id}`
    })
  },

  // 编辑记录
  editRecord(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/create-record/create-record?id=${id}`
    })
  },

  // 删除记录
  async deleteRecord(e) {
    const id = e.currentTarget.dataset.id
    
    const confirm = await util.showModal('确认删除', '确定要删除这条用车记录吗？')
    if (!confirm) return
    
    try {
      util.showLoading('删除中...')
      const res = await util.request(`/car-records/${id}`, {
        method: 'DELETE'
      })
      
      if (res.code === 200) {
        util.showToast('删除成功', 'success')
        this.refreshRecords()
      } else {
        util.showToast(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      util.showToast('删除失败，请重试')
    } finally {
      util.hideLoading()
    }
  },

  // 创建新记录
  createRecord() {
    wx.navigateTo({
      url: '/pages/create-record/create-record'
    })
  },

  // 格式化金额
  formatAmount(amount) {
    return parseFloat(amount || 0).toFixed(2)
  },

  // 格式化日期
  formatDate(dateStr) {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    return util.formatDate(date)
  }
})